<?php
session_start();

require_once '../../include/common.inc.php';
switch($act){
	// 获取软件过来的链接，验证token有效存在则注册后登录 Author @liuhuiwu<13750088090@sina.cn>
	// 注意ie浏览器不支持此格式跳转
	// {exit("<script>top.location.reload(true);location.href='./';</script>");}
	case "token":
		$url = $ucurl . '/api/internalUserInfo';
		$access_token = $_REQUEST['token'];
		$_SESSION['access_token'] = $_REQUEST['token'];

		if (empty($access_token)) {header("location:" . $_SERVER['HOST_NAME'] . "/room/m/minilogin.php");exit;}

		$post_data['access_token']       = $access_token;
		$time=time();
		$post_data['time']      = $time;
		$post_data['sign']      = md5($access_token.$time.'33f6ae6da9125c21');
		$res = request_post($url, $post_data);
		$result = json_decode($res,true);


		if ($result['status'] == 'false'|| $result['status'] == false ) {header("location:" . $_SERVER['HOST_NAME'] . "/room/m/minilogin.php");exit;}
		$password = '';

		$msg=token_login($result,$password);

		if($msg===true){ header("location:" . $_SERVER['HOST_NAME'] . "/room/m/");exit;}

		else{ echo "<script>top.layer.msg('{$msg}',{shift: 6});layer.msg('{$msg}',{shift: 6});</script>";}

	break;
	case "login":
		$msg=user_login($username,$password);
//		if($msg===true){header("location:" . $_SERVER['HOST_NAME'] . "/room");exit;}
		if($msg===true){exit("<script>location.reload(true);location.href='./';</script>");}
		else{ echo "<script>alert('{$msg}');history.go(-1);</script>";}
	break;
	case "reg":
		if($_SESSION['mcode'] != $mcode)
			exit("<script>alert('验证码错误！');location.href='?'</script>");
		$guestexp = '^Guest|'.$cfg['config']['regban']."Guest";
		if(preg_match("/\s+|{$guestexp}/is", $u))
		exit("<script>alert('用户名禁用！');</script>");
		
		$query=$db->query("select uid from {$tablepre}members where username='{$u}' limit 1");
		if($db->num_rows($query))exit("<script>alert('用户名已经被使用!换一个，如{$u}1985');location.href='?'</script>");
		
		$regtime=gdate();
		// 传递password变量 start 20161111 Author @liuhuiwu<13750088090@sina.cn>
		// $p=md5($p);
		$password = $p;
		$p=md5($password);
		// 传递password变量 end 20161111 Author @liuhuiwu<13750088090@sina.cn>
		if(isset($_COOKIE['tg'])) {
			$tuser=userinfo($_COOKIE['tg'],'{username}');
		} else {
			$tuser = rand_kefu();
		}
		if($cfg['config']['regaudit']=='1')$state='0';
		else $state='1';


		// 用户中心注册start20161111 Author @liuhuiwu<13750088090@sina.cn>
		$url = $ucurl . '/oauth/register';
		$data = array(
			'grant_type' => 'register',
			'client_id' => '7',
			'client_secret' => 'o8fFtWOY8bytC3nFGaTVCpWif01Z3viiJpWscIpBua',
			'username' => $u,
			'password' => $password,
			'repassword' => $password,
			'register_type' => 'livePC',
			'phone' => $phone,
			'key' => $_SESSION['mcode'],
		);
		$res = request_post($url, $data);
		$res =json_decode($res,true);

		if(isset($res['status'])&&$res['status'] == 'false'){
			exit("<script>alert('".$res['message']."');location.href='?'</script>");
		}

		if(isset($res['state'])&&$res['state'] == false){
			exit("<script>alert('".$res['msg']."');location.href='?'</script>");
		}


		// 用户中心注册end20161111 Author @liuhuiwu<13750088090@sina.cn>

//		$db->query("insert into {$tablepre}members(username,password,sex,email,regdate,regip,lastvisit,lastactivity,gold,realname,gid,phone,fuser,tuser,state)	values('$u','$p','2','$email','$regtime','$onlineip','$regtime','$regtime','0','$qq','1','$phone','$tuser','$tuser','$state')");
		$db->query("insert into {$tablepre}members(username,password,sex,email,regdate,regip,lastvisit,lastactivity,gold,realname,gid,phone,fuser,tuser,state)	values('$u','$p','2','','$regtime','$onlineip','$regtime','$regtime','0','','1','$phone','$tuser','$tuser','$state')");
		$uid=$db->insert_id();
		$db->query("replace into {$tablepre}memberfields (uid,nickname)	values('$uid','$u')	");
		
		$db->query("insert into  {$tablepre}msgs(rid,ugid,uid,uname,tuid,tname,mtime,ip,msg,type)
	values('{$cfg[config][id]}','1','{$uid}','{$u}','{$cfg[config][defvideo]}','{$cfg[config][defvideonick]}','".gdate()."','{$onlineip}','用户注册','2')
		");

		$msg=user_login($u,$p2);

		if($msg===true){exit("<script>location.reload(true);location.href='./';</script>");}
		else{ echo "<script>alert('注册成功')</script>";}
	break;
	case "logout":
		unset($_SESSION['login_uid']);
		unset($_SESSION['login_user']);
		session_destroy(); 
		header("location:index.php");
	break;
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title><?=$cfg['config']['title']?> 迷你登录</title>
<meta name="viewport" content="width=device-width,height=device-height,initial-scale=1, maximum-scale=1,user-scalable=no">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-capable" content="default">
<link href="css/style.css" rel="stylesheet" type="text/css"  />
<script src="../script/jquery.min.js"></script>
<script src="script/flexible.js"></script>
<!-- <script src="../script/layer.js"></script> -->
</head>

<body>
<div class="login">
    
    <div class="header" style="border:none;">
        <div class="switch cf" id="switch" style="position: relative;left: 0;">
            <a class="switch_btn_focus" id="switch_qlogin" href="javascript:void(0);" tabindex="7" style="margin: 0;">登录</a>
			<a class="switch_btn" id="switch_login" href="javascript:void(0);" style="margin: 0;" tabindex="8">注册</a>
        </div>
    </div>    
  
    
    <div class="web_qr_login" id="web_qr_login" style="display: block;">    

            <!--登录-->
            <div class="web_login" id="web_login">
               
               
               <div class="login-box">
    
            
			<div class="login_form">
				<form action="?act=login" method="post" enctype="application/x-www-form-urlencoded"  name="loginform"  id="login_form" class="loginForm" >
                <div class="uinArea" id="uinArea"> 
                <div class="inputOuter2" id="uArea">
                    <span class="ic"><i class="ic-form"></i></span>
                    <input type="text" id="username"  name="username" class="inputstyle2" placeholder="请输入用户名"/>
                </div>
                </div>
                <div class="pwdArea" id="pwdArea">
               <div class="inputOuter2" id="pArea">
                    <span class="ic"><i class="ic-form psw"></i></span>
                    <input type="password" id="password"   name="password" class="inputstyle2" placeholder="请输入密码"/>
                </div>
                </div>
<!--                <div class="agree ano"><i class="ic ic-check ano on"></i><a class="forget-psw fr" href="#">忘记密码？</a>记住密码</div>-->
                <div style="padding: 0 0 20px 0;overflow: hidden;"><input type="submit" value="马上登录" class="button_blue"/></div>
              </form>
              <a href="letter.html" class="to-investor">致投资者的一封信<i class="ic-angle-rep"></i></a>
           </div>
           
            	</div>
               
            </div>
            <!--登录end-->
  </div>

  <!--注册-->
    <div class="qlogin" id="qlogin" style="display: none; ">
   
    <div class="web_login"> <form action="?act=reg" method="post" enctype="application/x-www-form-urlencoded" id="regUser">
        <ul class="reg_form" id="reg-ul">
        		 <div id="userCue" class="cue" style="display:none;"></div>
                <li>
                    <div class="inputOuter2">
                        <span class="ic"><i class="ic-form"></i></span>
                        <input type="text" id="u"   name="u" maxlength="16" class="inputstyle2" placeholder="请输入用户名"/>
                    </div>
                    
                </li>
                <li>
                    <div class="inputOuter2">
                        <span class="ic"><i class="ic-form psw"></i></span>
                        <input type="password" id="p"   name="p" maxlength="16" class="inputstyle2" placeholder="请输入密码"/>
                    </div>
                    
                </li>
                <li>
                    <div class="inputOuter2">
                        <span class="ic"><i class="ic-form psw"></i></span>
                        <input type="password" id="p2"  name="p2" maxlength="16" class="inputstyle2" placeholder="请再次确认密码"/>
                    </div>
                    
                </li>
                
                <li>
                    <div class="inputOuter2">
                        <span class="ic"><i class="ic-form mob"></i></span>                       
                        <input type="text" id="phone"  name="phone" maxlength="11" class="inputstyle2" placeholder="请输入手机号码"/>
                    </div>
                   
                </li>  
                <li style="padding: 0 0 10px 0;">
                    <div class="inputOuter2">                       
                        <input type="text" id="mcode" name="mcode" maxlength="11" class="inputstyle2 msg" placeholder="请输入短信验证码"/>
						<a href="javascript:void(0);" onclick="sendSMS()" class="sendsms" id="sendsms">发送验证码</a>
                    </div>
<!--					<input type="hidden" name="mcode" value="" id="exmcode">-->
				</li>
                <li>
                    <div class="agree"><i class="ic-check on"></i>同意用户协议</div>
                </li>             
                <li>
                    <div class="inputArea">
                        <input type="button" id="reg" class="button_blue" value="提交"/>
                    </div>
                </li>
                <li>
                    <a href="letter.html" class="to-investor">致投资者的一封信<i class="ic-angle-rep"></i></a>
                </li>
                <div class="cl"></div>
            </ul></form>
           
    
    </div>
   
    
    </div>
    <!--注册end-->
</div>
<script>
var ds;
function sendSMS() {


	var phone = $('input[name="phone"]').val();
	var res = validatemobile(phone);
	if(!res) {
		return;
	}

	// 调用短信第三方接口start 20161112 Author @liuhuiwu<13750088090@sina.cn>
	$.ajax({
		type: "post",
		url: '../sms.php',
		dataType: "json",
		data: {"phone": phone},
		success: function(d) {
			var obj = JSON.parse(d);

			if (obj.MsgCode == '1') {
				//layer.msg('验证码发送成功', 2, 1);
				alert('验证码发送成功');
				ds = setInterval('countdown()', 1000);
			} else if (obj.MsgCode == '-2') {
				//layer.msg('验证码发送失败', 2, 0);
				alert('一个手机号只能注册一次');
			} else {
				alert('验证码发送失败');
			}
		}
	});
	// 调用短信第三方接口end 20161112 Author @liuhuiwu<13750088090@sina.cn>
}
function countdown() {
	var times = $('#sendsms').html();
	times = parseInt(times);
	var isint = isNaN(times);
	if(isint) {
	  times = 61;
	  $('#sendsms').removeAttr('onclick');
	}
	times = times - 1;
	if(times <= -1) {
		clearInterval(ds);
		$('#sendsms').html('发送验证码');
		$('#sendsms').attr('onclick', 'sendSMS()');
	} else {
		$('#sendsms').html(times);
		$('#sendsms').attr('');
	}
}
function validatemobile(mobile) {
	if(mobile.length==0) {
		//layer.msg('请输入手机号码', 2, 0);
		alert('请输入手机号码');
		return false;
	}    
	if(mobile.length!=11) {
		//layer.msg('请输入有效的手机号码', 2, 0);
		alert('请输入有效的手机号码');
		return false;
	}

	var myreg = /^0?1[3|4|5|8][0-9]\d{8}$/;
	if(!myreg.test(mobile)) {
		//layer.msg('请输入有效的手机号码', 2, 0);
		alert('请输入有效的手机号码');
		return false;
	}
	return true;
}
$(function(){
	
	$('#switch_qlogin').click(function(){
		$('#switch_login').removeClass("switch_btn_focus").addClass('switch_btn');
		$('#switch_qlogin').removeClass("switch_btn").addClass('switch_btn_focus');
		$('#switch_bottom').animate({left:'0px',width:'66px'});
		$('#qlogin').css('display','none');
		$('#web_qr_login').css('display','block');
		try{
		parent.layer.iframeAuto(parent.layer.getFrameIndex(window.name));
		}catch(e){}
		});
	$('#switch_login').click(function(){
		
		$('#switch_login').removeClass("switch_btn").addClass('switch_btn_focus');
		$('#switch_qlogin').removeClass("switch_btn_focus").addClass('switch_btn');
		$('#switch_bottom').animate({left:'152px',width:'66px'});
		
		$('#qlogin').css('display','block');
		$('#web_qr_login').css('display','none');
		try{
		parent.layer.iframeAuto(parent.layer.getFrameIndex(window.name));
		}catch(e){}
		});
		if(getParam("a")=='0')
		{
			$('#switch_login').trigger('click');
		}
        $('.ic-check').click(function(){
            $(this).toggleClass('on');
        })

	});
	
function logintab(){
	scrollTo(0);
	$('#switch_qlogin').removeClass("switch_btn_focus").addClass('switch_btn');
	$('#switch_login').removeClass("switch_btn").addClass('switch_btn_focus');
	$('#switch_bottom').animate({left:'152px',width:'66px'});
	$('#qlogin').css('display','none');
	$('#web_qr_login').css('display','block');
	
}


//根据参数名获得该参数 pname等于想要的参数名 
function getParam(pname) { 
    var params = location.search.substr(1); // 获取参数 平且去掉？ 
    var ArrParam = params.split('&'); 
    if (ArrParam.length == 1) { 
        //只有一个参数的情况 
        return params.split('=')[1]; 
    } 
    else { 
         //多个参数参数的情况 
        for (var i = 0; i < ArrParam.length; i++) { 
            if (ArrParam[i].split('=')[0] == pname) { 
                return ArrParam[i].split('=')[1]; 
            } 
        } 
    } 
}  


var reMethod = "GET",
	pwdmin = 6;

$(document).ready(function() {


	$('#reg').click(function() {

		if ($('#u').val() == "") {
			$('#u').focus().css({
				border: "1px solid red",
				boxShadow: "0 0 2px red"
			});

			$('#userCue').html("<font color='red'><b>×用户名不能为空</b></font>").show();
			return false;
		}



		if ($('#u').val().length < 5 || $('#u').val().length > 16) {
			$('#u').focus().css({
				border: "1px solid red",
				boxShadow: "0 0 2px red"
			});
			$('#userCue').html("<font color='red'><b>×用户名位5-16字符</b></font>").show();
			return false;
		}

		var userExp = /^(\d|[a-zA-Z])*((\d[a-zA-Z])|([a-zA-Z]\d))(\d|[a-zA-Z])*$/;
		if(!userExp.test($('#u').val())){
			$('#userCue').html("<font color='red'><b>×账号必须字母和数字组合</b></font>").show();
			return;
		}


		var phone = $('input[name="phone"]').val();
		var res = validatemobile(phone);
		if(!res) {
			return;
		}

		$.ajax({
			type: reMethod,
			url: '../ajax.php?act=regcheck',
			data: "username=" + $("#u").val() + '&temp=' + new Date(),
			dataType: 'html',
			success: function(result) {

				if (result!='1') {
					$('#u').focus().css({
						border: "1px solid red",
						boxShadow: "0 0 2px red"
					});
					if(result=='-1')
					$("#userCue").html("<font color='red'><b>×用户名含关键字，不能使用！</b></font>").show();
					else if(result=='0')
					$("#userCue").html("<font color='red'><b>×用户名被占用！</b></font>").show();
					return false;
				} else {
					$('#u').css({
						border: "1px solid #D7D7D7",
						boxShadow: "none"
					});
				}

			}
		});


		if ($('#p').val().length < pwdmin) {
			$('#p').focus();
			$('#userCue').html("<font color='red'><b>×密码不能小于" + pwdmin + "位</b></font>").show();
			return false;
		}
		if ($('#p2').val() != $('#p').val()) {
			$('#p2').focus();
			$('#userCue').html("<font color='red'><b>×两次密码不一致！</b></font>").show();
			return false;
		}
//		var semail=/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/;
//		if($('#email').val().length < 7 || !semail.test( $('#email').val())){
//			$('#userCue').html("<font color='red'><b>×邮箱格式错误！</b></font>");
//			$('#email').focus().css({
//				border: "1px solid red",
//				boxShadow: "0 0 2px red"
//			});
//			return false;
//		}
//		var sqq = /^[1-9]{1}[0-9]{4,9}$/;
//		if (!sqq.test($('#qq').val()) || $('#qq').val().length < 5 || $('#qq').val().length > 12) {
//			$('#qq').focus().css({
//				border: "1px solid red",
//				boxShadow: "0 0 2px red"
//			});
//			$('#userCue').html("<font color='red'><b>×QQ号码格式不正确</b></font>");
//			return false;
//		} else {
//			$('#qq').css({
//				border: "1px solid #D7D7D7",
//				boxShadow: "none"
//			});
//
//		}

		$('#regUser').submit();
	});
	

});
</script>
</body>
</html>
